package com.dqy.twserver.server.handle.ehandle.frame;

import com.dqy.twserver.server.dto.GameDto;
import com.dqy.twserver.server.handle.ehandle.GameEventHandle;
import com.dqy.twserver.server.handle.ehandle.mutil.GameEventCreateTerr;
import com.dqy.twserver.server.support.Player;
import com.dqy.twserver.server.support.SupportMap;
import io.netty.channel.socket.nio.NioSocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

public class GameEventFrameSycnHandle implements GameEventHandle {
    static Logger logger = LoggerFactory.getLogger(GameEventFrameSycnHandle.class);

    @Override
    public void handle(GameDto req, NioSocketChannel channel) throws Exception {
        logger.info("[GameEventFrameSycnHandle] start");
        int rid = roomIdToRid(req.getRoomId());
        String playerName = req.getPlayerName();

        List<Player> playerList = SupportMap.roomMap.get(rid).getPlayerList();
        int minFrame=Integer.MAX_VALUE;
        int thisFrame=0;
        for(Player p:playerList){
            if(!playerName.equals(p.getPlayerName()))
                minFrame=Math.min(minFrame,p.getFrameNum());
            else
                thisFrame=p.getFrameNum();
        }
        logger.info("thisF={} , minF={}",thisFrame,minFrame);

        if(thisFrame-minFrame >= 1){
            //客户端当前帧需要等待
            GameDto build = GameDto.build(400, null, -1);
            channel.writeAndFlush(build);
        }else {
            Player player = SupportMap.playerMap.get(playerName);
            player.setFrameNum(thisFrame+1);
            GameDto build = GameDto.build(200, null, -1);
            channel.writeAndFlush(build);
        }

        logger.info("[GameEventFrameSycnHandle] end");
    }
}
